<template>
  <div>
    <el-card style="border-radius: 12px">
      <el-form inline style="margin-top: 20px">
        <el-form-item label="部门：">
          <el-select placeholder="请选择" v-model="SdepNumber" filterable>
            <el-option
              v-for="department in AlldepartmentsData"
              :key="department.departmentNumber"
              :value="department.departmentNumber"
              :label="department.departmentName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工号：">
          <el-input
            placeholder="请输入部门成员编号"
            v-model="SdepUserNumber"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="姓名:">
          <el-input
            placeholder="请输入部门成员姓名"
            v-model="SdepUserName"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="Search"
            @click="getdepartmentMemberData()"
            v-button="'btn.Member.search'"
          >
            搜索
          </el-button>
          <el-button
            @click="
              ;(SdepNumber = ''),
                (SdepUserName = ''),
                (SdepUserNumber = ''),
                getdepartmentMemberData()
            "
          >
            重置
          </el-button>
        </el-form-item>
        <el-form-item style="text-align: right">
          <el-row :gutter="20">
            <el-col :span="4">
              <el-button
                type="primary"
                @click="departmentMemberView"
                v-button="'btn.Member.add'"
              >
                添加部门成员
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <el-table :data="departmentMemberData" style="margin: 10px 0px" border>
        <el-table-column
          label="序号"
          align="center"
          type="index"
          prop="index"
          hidden="false"
        ></el-table-column>
        <el-table-column
          label="部门"
          align="center"
          prop="department"
        ></el-table-column>
        <el-table-column
          label="成员编号"
          align="center"
          prop="jobNumber"
        ></el-table-column>
        <el-table-column
          label="成员"
          align="center"
          prop="userName"
        ></el-table-column>
        <el-table-column
          label="成员电话"
          align="center"
          prop="userMobile"
        ></el-table-column>
        <el-table-column label="操作" align="center">
          <template #="{ row, $index }">
            <!-- <h1>{{ row }}</h1> -->
            <el-tooltip
              effect="dark"
              content="删除部门成员"
              placement="top"
              :enterable="false"
            >
              <el-popconfirm
                :title="`删除: ${row.userName}?`"
                icon="Delete"
                icon-color="red"
                @confirm="deletedepartmentMember(row.id)"
              >
                <template #reference>
                  <el-button
                    size="small"
                    type="danger"
                    icon="Delete"
                    v-button="'btn.Member.delete'"
                  ></el-button>
                </template>
                /
              </el-popconfirm>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 
   v-model:current-page ：当前页
   v-model:page-size：设置每页展示数据的条数
         -->
      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[5, 10, 15, 20]"
        :small="false"
        :disabled="false"
        :background="true"
        layout="prev, pager, next, jumper, -> ,total, sizes"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="getdepartmentMemberData"
      />
    </el-card>
    <!-- 添加部门成员对话框 -->
    <el-dialog :title="'新增部门成员'" v-model="addDialogVisible" width="30%">
      <el-form
        style="width: 90%"
        label-width="100px"
        :model="departmentMemberParams"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item label="部门">
          <el-select
            filterable
            placeholder="请选择部门（下拉选框）"
            v-model="departmentMemberParams.departmentNumber"
          >
            <el-option
              v-for="depart in AlldepartmentsData"
              :key="depart.departmentNumber"
              :value="depart.departmentNumber"
              :label="depart.departmentName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="成员编号" prop="jobNumber">
          <el-input
            placeholder="请输入成员编号"
            v-model="departmentMemberParams.jobNumber"
          ></el-input>
        </el-form-item>
        <el-form-item label="成员名称" prop="userName">
          <el-input
            placeholder="请输入成员名称"
            v-model="departmentMemberParams.userName"
          ></el-input>
        </el-form-item>
        <el-form-item label="成员电话" prop="userMobile">
          <el-input
            placeholder="部门成员电话"
            v-model="departmentMemberParams.userMobile"
          ></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="addOrUpdatedepartmentMember">
          确 定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
import { reqGetAlldepartment } from '@/api/department'
import type { Alldepartment, departmentlists } from '@/api/department/type'
import {
  reqdepartmentMembersData,
  reqAddOrUpdatedepartmentMemberData,
  reqDeletedepartmentMemberData,
} from '@/api/departmentmember'
import type {
  departmentMembers,
  departmentMemberInformationResponseData,
  departmentMemberInformation,
  deleteMemberList,
  ResponseData,
} from '@/api/departmentmember/type'
// 当前页码
let pageNo = ref<number>(1)
// 定义每页展示数据
let limit = ref<number>(5)
// 定义展示数据的总数
let total = ref<number>(0)

// 定义已有部门成员的数据
let departmentMemberData = ref<departmentMembers>([])

let AlldepartmentsData = ref<departmentlists>([])

let departmentMemberParams = reactive<any>({
  departmentNumber: '',
  department: '',
  jobNumber: '',
  userName: '',
  userMobile: '',
})

const validatorDepartment = (rule: any, value: any, callback: any) => {
  if (value) {
    callback()
  } else {
    callback(new Error('部门不能为空'))
  }
}

const validatorJobNumber = (rule: any, value: any, callback: any) => {
  if (value) {
    callback()
  } else {
    callback(new Error('工号不能为空'))
  }
}

const validatorMobile = (rule: any, value: any, callback: any) => {
  let reg = /^1[34578]\d{9}$/
  let n = reg.test(value)
  if (value && n) {
    callback()
  } else if (!value) {
    callback(new Error('电话不能为空'))
  } else {
    callback(new Error('电话格式有误'))
  }
}

const validatortMemberName = (rule: any, value: any, callback: any) => {
  if (value) {
    callback()
  } else {
    callback(new Error('成员不能为空'))
  }
}
const rules = {
  department: [
    { required: true, trigger: 'blur', validator: validatorDepartment },
  ],
  jobNumber: [
    {
      required: true,
      type: 'number',
      trigger: 'blur',
      validator: validatorJobNumber,
    },
  ],
  userName: [
    { required: true, trigger: 'blur', validator: validatortMemberName },
  ],

  userMobile: [
    {
      required: true,
      type: 'number',
      trigger: 'blur',
      validator: validatorMobile,
    },
  ],
}
//添加部门成员对话框
let addDialogVisible = ref<boolean>(false)

// 获取el-form 组件实例
let formRef = ref()

const getAlldepartment = async () => {
  let result: Alldepartment = await reqGetAlldepartment()
  if (result.code == 200) {
    // 存储已有品牌的总数
    AlldepartmentsData.value = result.data
  }
}

const SdepNumber = ref<string>()
const SdepUserName = ref<string>()
const SdepUserNumber = ref<string>()
// main区域的数据
const getdepartmentMemberData = async (page: number = 1) => {
  pageNo.value = page
  let params = {
    departmentNumber: SdepNumber.value ? SdepNumber.value : '',
    name: SdepUserName.value ? SdepUserName.value : '',
    jobNumber: SdepUserNumber.value ? SdepUserNumber.value : '',
    currentPage: pageNo.value,
    pageSize: limit.value,
  }
  let result: departmentMemberInformationResponseData =
    await reqdepartmentMembersData(params)
  console.log(result)
  if (result.code == 200) {
    // 存储已有品牌的总数
    total.value = result.data.total
    departmentMemberData.value = result.data.records
  }
}
// 组件挂载完毕
onMounted(() => {
  getAlldepartment()
  getdepartmentMemberData()
})

// 更改分页器大小
const handleSizeChange = () => {
  getdepartmentMemberData()
}
// 添加部门成员方法
const addOrUpdatedepartmentMember = async () => {
  // 发送请求之前对整个表单进行校验
  await formRef.value.validate()
  console.log(departmentMemberParams)
  const sedepartment = AlldepartmentsData.value.find((department) => {
    return (
      department.departmentNumber === departmentMemberParams.departmentNumber
    )
  })
  departmentMemberParams.department = sedepartment?.departmentName
  console.log(departmentMemberParams)
  let result: ResponseData = await reqAddOrUpdatedepartmentMemberData(
    departmentMemberParams,
  )
  console.log(result)

  if (result.code == 200) {
    addDialogVisible.value = false
    ElNotification({
      type: 'success',
      message: '添加部门成员成功',
    }),
      // 再次发请求更新所有数据
      getdepartmentMemberData(departmentMemberParams.id ? pageNo.value : 1)
  } else {
    ElNotification({
      type: 'error',
      message: '用户个人信息不匹配',
    })
  }
}

let deleteListId = ref<number[]>([])

// 删除确认框按钮回调
const deletedepartmentMember = async (id: number) => {
  // 点击确定按钮删除请求发送
  deleteListId.value?.push(id)
  console.log(deleteListId)
  let result = await reqDeletedepartmentMemberData(deleteListId.value)
  console.log(result)

  if (result.code == 200) {
    ElNotification({
      type: 'success',
      message: '删除成功',
    })
    getdepartmentMemberData(
      departmentMemberData.value.length > 1 ? pageNo.value : pageNo.value - 1,
    )
  } else {
    ElNotification({
      type: 'error',
      message: '删除失败',
    })
  }
}
// 表单取消按钮
const cancel = () => {
  addDialogVisible.value = false
}
// 表单确定按钮
const departmentMemberView = () => {
  addDialogVisible.value = true
  //  清空收集 的数据
  ;(departmentMemberParams.departmentNumber = ''),
    (departmentMemberParams.department = ''),
    (departmentMemberParams.jobNumber = ''),
    (departmentMemberParams.userName = ''),
    (departmentMemberParams.userMobile = '')
  nextTick(() => {
    for (const key in departmentMemberParams) {
      formRef.value.clearValidate(key)
      console.log(key)
    }
  })
}
</script>

<style scoped lang="scss"></style>
